import { defineStore } from 'pinia'
import { store } from '../index'
import { getUser } from '@/api/login/index.js'
import { UserType } from '@/api/login/types'
import { ElMessageBox } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { loginOutApi } from '@/api/login'
import { useTagsViewStore } from './tagsView'
import router from '@/router'
import {session } from '@/utils/storage'
import GLB_CONFIG from '@/config'

interface UserState {
  userInfo?: UserType
  tokenKey: string
  token: string
  loginSource: string | null
  roleRouters?: string[] | AppCustomRouteRecordRaw[]
}

export const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      userInfo: undefined, // 登录人信息
      tokenKey: session.getItem('tokenKey') || 'Authorization', // 登录token的key
      token:session.getItem('token') ||'Bearer eyJraWQiOiIzNDBlN2IxNC0yMGI4LTQyZDMtYWJiZi1jMzI5MmU1NTVlODEiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhZG1pbmlzdHJhdG9yIiwiaXNBYmxlIjoxLCJpc3MiOiJodHRwczpcL1wvbG9naW4tdGVzdC50LWFhcm9uLmNvbSIsImF1ZCI6InR1b2hlbmctYWlycG9ydC1hZG1pbiIsIm5iZiI6MTcyNjc5Mzc0OSwib1VzZXJJZCI6NzQzLCJzY29wZSI6WyJ0dW9oZW5nLWFpcnBvcnQtYWRtaW4iLCJ0dW9oZW5nLWFpcnBvcnQtbXAiXSwiY2xpZW50Um9sZUxpc3QiOiJbe1wiY2xpZW50SWRcIjpcInR1b2hlbmctYWlycG9ydC1hZG1pblwiLFwicm9sZUlkXCI6MX0se1wiY2xpZW50SWRcIjpcInR1b2hlbmctYWlycG9ydC1tcFwiLFwicm9sZUlkXCI6MX1dIiwiZXhwIjoxNzI2ODgwMTQ5LCJpc0V4cGlyZSI6MSwiaWF0IjoxNzI2NzkzNzQ5LCJ1c2VybmFtZSI6ImFkbWluaXN0cmF0b3IifQ.wHw0BbNaLSacrmgZx41LclrDh0EfqMlSyjQi8XHLma0Zuuv6d-UU94zYf2cDoMsGkRl_1_xQBCqLKZXUABdhADoSVRIUpUBl3YoR9wnT9F-R2ASNsdG3-jYRxABXGB-1lC_hAiLWvctNbuf8vEfsIuogB61zuUdaNf1fFcaEzItuMBLGw_p0yJwZ_kbCrlRQpBr54IDRpSbWPvMB8w_fO414iR0kqUE1om4NSY2w-Yn41AMRDVb3nflpA5WRJxtsgjyvxtaYrkfSzg8n_k89IwaCsfArhKpLbO1Vf6U_EQgUAoP8gF6sNe49zyAKxp9oxb3IbxfAtBb04BUH46hSdQ', // 登录token
      roleRouters: undefined, // 角色路由
      loginSource:session.getItem('loginSource') || 'oidc' ,// 登录方式
    }
  },
  getters: {
    getLoginSource(): string | null {
      return this.loginSource
    },
    getTokenKey(): string {
      return this.tokenKey
    },
    getToken(): string {
      return this.token
    },
    getUserInfo(): UserType | undefined {
      return this.userInfo
    },
    getRoleRouters(): string[] | AppCustomRouteRecordRaw[] | undefined {
      return this.roleRouters
    }
  },
  actions: {
    //获取登录人信息
    async getUserInfos(): Promise<unknown> {
      return new Promise<void>(async (resolve) => {
        const res = await getUser()
        if (res.code === 0) {
          this.setUserInfo({ hasLogin: true, ...res.data })
        } else {
          this.setUserInfo()
        }
        return resolve()
      })
    },
    setLoginSource(loginSource: string | null) {
      this.loginSource = loginSource
      session.setItem('loginSource', loginSource)
    },
    setTokenKey(tokenKey: string) {
      this.tokenKey = tokenKey
      session.setItem('tokenKey', tokenKey)
    },
    setToken(token: string) {
      console.log('走了setToken===')
      this.token = token
      session.setItem(GLB_CONFIG.tokenStoreName, token)
    },
    setUserInfo(userInfo?: UserType) {
      this.userInfo = userInfo
    },
    setRoleRouters(roleRouters: string[] | AppCustomRouteRecordRaw[]) {
      this.roleRouters = roleRouters
    },
    logoutConfirm() {
      const { t } = useI18n()
      ElMessageBox.confirm(t('common.loginOutMessage'), t('common.reminder'), {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      })
        .then(async () => {
          const res = await loginOutApi().catch(() => {})
          if (res) {
          this.reset()
          }
        })
        .catch(() => {})
    },
    reset() {
      const tagsViewStore = useTagsViewStore()
      tagsViewStore.delAllViews()
      this.setToken('')
      this.setUserInfo(undefined)
      this.setRoleRouters([])
      router.replace('/login')
    },
    logout() {
      this.reset()
    }
  },
  persist: true
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
